{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style>
	.ns-discount { display: flex; justify-content: space-between; height: 34px; line-height: 34px; padding: 5px 15px; background-color: #F6FBFD; border: 1px dashed #BCE8F1; }
</style>
{/block}
{block name="main"}
<div class="layui-collapse ns-tips">
	<div class="layui-colla-item">
		<h2 class="layui-colla-title">操作提示</h2>
		<ul class="layui-colla-content layui-show">
			<li>满减活动包括店铺所有商品，活动时间不能和已有活动重叠</li>
			<li>每添加一个规则都需点击确定规则设置按钮，生成一条规则，提交之后才可成功添加</li>
			<li>点击确定规则设置按钮生成的规则都有一个删除按钮，如不需要该条规则点击删除按钮即可删除</li>
		</ul>
	</div>
</div>

<div class="layui-form ns-form">
	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动名称：</label>
		<div class="layui-input-block">
			<input type="text" name="manjian_name" lay-verify="required|len" value="{$manjian_info.manjian_name}" placeholder="请输入活动名称" class="layui-input ns-len-long" autocomplete="off">
		</div>
		<div class="ns-word-aux">
			<p>活动名称最多为25个字符</p>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>开始时间：</label>
		<div class="layui-input-block ns-len-mid">
			<input type="text" {if condition="$manjian_info.status == 1"}disabled {/if} value="{:date('Y-m-d H:i:s', $manjian_info.start_time)}" class="layui-input" name="start_time" lay-verify="required" id="start_time" autocomplete="off" readonly>
			<i class="ns-calendar"></i>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>结束时间：</label>
		<div class="layui-input-block ns-len-mid end_time">
			<input type="text" {if condition="$manjian_info.status == 1"}disabled {/if} value="{:date('Y-m-d H:i:s', $manjian_info.end_time)}" class="layui-input" name="end_time" lay-verify="required|times" id="end_time" autocomplete="off" readonly>
			<i class="ns-calendar"></i>
		</div>

		<div class="ns-word-aux">
			{if condition="$manjian_info.status == 1"}
			<p>活动进行中时间不可更改</p>
			{else/}
			<p>结束时间不能小于开始时间，也不能小于当前时间</p>
			{/if}
		</div>
	</div>

	<div class="layui-form-item">
		<div class="layui-form">
			<div class="layui-form-item">
				<label class="layui-form-label">满减规则：</label>

				<div class="ns-discount-box">
				</div>

				<div class="layui-input-block ns-form-row">
					<span class="layui-form-mid">单笔订单满</span>
					<div class="layui-input-inline">
						<input type="number" class="layui-input ns-len-short" id="money" lay-verify="num" autocomplete="off">
					</div>
					<span class="layui-form-mid">元，立减现金</span>
					<div class="layui-input-inline">
						<input type="number" class="layui-input ns-len-short" id="discount_money" lay-verify="num" autocomplete="off">
					</div>
					<span class="layui-form-mid">元</span>
				</div>

				<div class="ns-word-aux">
					<p>价格不能小于0，可保留两位小数</p>
				</div>
			</div>

			<div class="ns-form-row">
				<button class="layui-btn ns-bg-color" onclick="submitRule()">确定规则设置</button>
			</div>
		</div>
	</div>

	<div class="layui-form-item">
		<label class="layui-form-label"><span class="required">*</span>活动商品：</label>
		<div class="layui-input-block">
			<input type="radio" name="manjian_type" lay-filter="manjian_type" value="1" title="全部商品参与" {if $manjian_info.manjian_type == 1} checked {/if}>
			<input type="radio" name="manjian_type" lay-filter="manjian_type" value="2" title="指定商品参与" {if $manjian_info.manjian_type == 2} checked {/if}>
		</div>
	</div>

	{if $manjian_info.manjian_type == 1}
	<div class="layui-form-item goods_list" style="display:none">
		{else /}
		<div class="layui-form-item goods_list">
			{/if}
			<label class="layui-form-label"></label>
			<div class="layui-input-block">
				<!-- <table class="layui-table" id="goods" lay-skin="line" lay-size="lg">

                    <thead>
                    <tr>
                        <th>商品名称</th>
                        <th>商品价格(元)</th>
                        <th>库存</th>
                        <th>编辑</th>
                    </tr>
                    </thead>
                    <tbody>
                    {if empty($manjian_info.goods_list)}
                    <tr>
                        <td class="ns-goods-null" colspan="3">
                            <div class="goods-null">该活动还未选择商品</div>
                        </td>
                    </tr>
                    {else /}
                    {foreach $manjian_info.goods_list as $v}
                    <tr data-sku_id="{$v.goods_id}">
                        <td>{$v.goods_name}</td>
                        <td>{$v.price}</td>
                        <td>{$v.goods_stock}</td>
                        <td><button class="layui-btn" onclick="delRule(this)">删除</button></td>
                    </tr>
                    {/foreach}
                    {/if}
                    </tbody>
                </table> -->
				<table id="selected_sku_list"></table>

				<button class="layui-btn ns-bg-color" onclick="addGoods()">选择商品</button>
			</div>
		</div>
		<input type="hidden" name="goods_ids">

		<div class="layui-form-item">
			<label class="layui-form-label">备注：</label>
			<div class="layui-input-block">
				<textarea name="remark" class="layui-textarea ns-len-long">{$manjian_info.remark}</textarea>
			</div>
		</div>

		<div class="ns-form-row">
			<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>
			<button class="layui-btn layui-btn-primary" onclick="back()">返回</button>
		</div>

		<input type="hidden" name="manjian_id" value="{$manjian_info.manjian_id}" />
		<input type="hidden" name="rule_json" value='{$manjian_info.rule_json}' id="rule_json" />
	</div>


	<!-- 操作 -->
	<script type="text/html" id="operation">
		<div class="ns-table-btn">
			<a class="layui-btn" onclick="delGoods({{d.goods_id}})">删除</a>
		</div>
	</script>
	{/block}
	{block name="script"}
	<script>
        var rule = JSON.parse($("#rule_json").val());
        for (var key in rule) {
            var html = '<div class="ns-discount ns-form-row">'+
                '<div class="ns-discount-con">'+
                '<p>单笔订单满<span class="required money-num">' + rule[key].money + '</span>元，立减现金<span class="required discount_money-num">' + rule[key].discount_money + '</span>元</p>'+
                '</div>'+
                '<div class="ns-discount-del">'+
                '<button class="layui-btn ns-bg-color" onclick="delRule(this)">删除</button>'+
                '</div>'+
                '</div>';
            $(".ns-discount-box").append(html);
        }

        var submitRule, delRule, selectedGoodsId = [], goods_id=[];
        var goods_list = {:json_encode($manjian_info.goods_list, JSON_UNESCAPED_UNICODE)};

        $.each(goods_list, function(index, item) {
            var id = item.goods_id;
            selectedGoodsId.push(id);
            goods_id.push(id);
        })
        $("input[name='goods_ids']").val(goods_id.toString());


        var table, form, laydate, repeat_flag = false; //防重复标识

        layui.use(['form', 'laydate'], function() {
            form = layui.form,
                laydate = layui.laydate,

                form.render();

            renderTable(goods_list); // 初始化表格

            laydate.render({
                elem: '#start_time',
                type: 'datetime'
            });

            laydate.render({
                elem: '#end_time',
                type: 'datetime'
            });


            //监听活动商品类型
            form.on('radio(manjian_type)', function(data){
                var value = data.value;

                if(value == 1){
                    $(".goods_list").hide();
                }
                if(value == 2){
                    $(".goods_list").show();
                }
            });

            /**
             * 表单验证
             */
            form.verify({
                len: function(value) {
                    if (value.length > 25) {
                        return "活动名称最多为25个字符!";
                    }
                },
                time: function(value) {
                    var now_time = (new Date()).getTime();
                    var time = (new Date(value)).getTime();
                    if (time < now_time) {
                        return '开始时间不能小于当前时间!';
                    }
                },
                times: function(value) {
                    var start_time = (new Date($("#start_time").val())).getTime();
                    var end_time = (new Date(value)).getTime();
                    if (start_time > end_time) {
                        return '结束时间不能小于开始时间!';
                    }
                },
                num: function(value) {
                    if (value == '') {
                        return;
                    }
                    if (value < 0) {
                        return '数字不能小于0!';
                    }
                    if (value * 100 % 1 != 0) {
                        return '数字最多保留两位小数!';
                    }
                }
            });

            /**
             * 监听提交
             */
            form.on('submit(save)', function(data) {
                var rule = {};
                var money_arr = [], discount_money_arr = [];
                for (var i=0; i<$(".ns-discount-box .ns-discount").length; i++) {
                    var money = $(".ns-discount-box .ns-discount").eq(i).find(".money-num").text();
                    var discount_money = $(".ns-discount-box .ns-discount").eq(i).find(".discount_money-num").text();
                    var obj = {'money': money, 'discount_money': discount_money};
                    rule[money] = obj;
                }

                data.field.rule_json = JSON.stringify(rule);

                if (repeat_flag) return;
                repeat_flag = true;

                $.ajax({
                    type: 'POST',
                    url: ns.url("manjian://shop/manjian/edit"),
                    data: data.field,
                    dataType: 'JSON',
                    success: function (res) {
                        repeat_flag = false;

                        if (res.code == 0) {
                            layer.confirm('编辑成功', {
                                title:'操作提示',
                                btn: ['返回列表', '继续操作'],
                                yes: function(){
                                    location.href = ns.url("manjian://shop/manjian/lists")
                                },
                                btn2: function() {
                                    location.reload();
                                }
                            });
                        } else if (res.code == -10077){
                            var key = res.data.key;
                            layer.confirm('在同一活动时间内，部分商品已参加其他的满减活动', {
                                title:'活动冲突提醒',
                                btn: ['取消', '查看详情'],
                                btn1: function(){
                                    location.href = ns.url("manjian://shop/manjian/add");
                                },
                                btn2: function() {
                                    location.href = ns.url("manjian://shop/manjian/conflict", {"key": key});
                                }
                            });
                        } else {
                            layer.msg(res.message);
                        }
                    }
                });
            });

            submitRule = function() {
                var money = $("#money").val().trim(),
                    discount_money = $("#discount_money").val().trim();

                if (Number(money) == "0" || Number(discount_money) == "0") {
                    layer.msg("满减金额不能为空！", {icon: 5, anim: 6});
                    return false;
                }
                if (Number(money) < 0 || Number(discount_money) < 0) {
                    layer.msg("金额不能小于0！", {icon: 5, anim: 6});
                    return false;
                }
                if (Number(money) * 100 % 1 != 0 || Number(discount_money) * 100 % 1 != 0) {
                    layer.msg("金额最多保留小数点后两位！", {icon: 5, anim: 6});
                    return false;
                }
                if (Number(money) < Number(discount_money)) {
                    layer.msg("立减金额不能大于满金额！", {icon: 5, anim: 6});
                    return false;
                }

                var html = '<div class="ns-discount ns-form-row">'+
                    '<div class="ns-discount-con">'+
                    '<p>单笔订单满<span class="required money-num">' + money + '</span>元，立减现金<span class="required discount_money-num">' + discount_money + '</span>元</p>'+
                    '</div>'+
                    '<div class="ns-discount-del">'+
                    '<button class="layui-btn ns-bg-color" onclick="delRule(this)">删除</button>'+
                    '</div>'+
                    '</div>';
                $(".ns-discount-box").append(html);
            };

            delRule = function(obj) {
                $(obj).parent().parent().remove();
            }
        });


        // 表格渲染
        function renderTable(goods_list) {
            //展示已知数据
            table = new Table({
                elem: '#selected_sku_list',
                cols: [
                    [{
                        field: 'goods_name',
                        title: '商品名称',
                        unresize: 'false',
                        width: '50%'
                    }, {
                        field: 'price',
                        title: '商品价格(元)',
                        unresize: 'false',
                        align: 'right',
                        width: '20%',
                        templet: function(data) {
                            return '￥' + data.price;
                        }
                    }, {
                        field: 'goods_stock',
                        title: '库存',
                        unresize: 'false',
                        align: 'center',
                        width: '20%'
                    }, {
                        title: '操作',
                        toolbar: '#operation',
                        unresize: 'false',
                        width: '10%'
                    }],
                ],
                data: goods_list,
            });
        }

        // 删除选中商品
        function delGoods(id) {
            var i, j;
            $.each(goods_list, function(index, item) {
                var goods_id = item.goods_id;

                if (id == goods_id) {
                    i = index;
                }
            })
            goods_list.splice(i, 1);
            renderTable(goods_list);

            $.each(selectedGoodsId, function(index, item) {
                if (id == item) {
                    j = index;
                }
            })
            selectedGoodsId.splice(j, 1);
            goods_id = selectedGoodsId;
            $("input[name='goods_ids']").val(goods_id.toString());
        }

        function addGoods(){
            goodsSelect(function (res) {

                var html = '';
                selectedGoodsId = [];
                goods_id = [];
                goods_list = [];
                for(var i=0;i<res.length;i++) {
                    goods_id.push(res[i].goods_id);
                    goods_list.push(res[i]);
                }
                renderTable(goods_list);
                $("input[name='goods_ids']").val(goods_id.toString());
                selectedGoodsId = goods_id;

            }, selectedGoodsId, {mode: "spu"});
        }

        function back() {
            location.href = ns.url("manjian://shop/manjian/lists");
        }
	</script>
	{/block}